package com.hand.yd24378.mybatis_train.service;

import com.github.pagehelper.PageHelper;
import com.hand.yd24378.mybatis_train.domain.User;
import com.hand.yd24378.mybatis_train.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author : WaveLee
 * @date : 2019/7/16 20:08
 * @description : 以下函数均未做异常拦截抛出
 */
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    /**
     * 插入用户
     * @param user
     * @return
     */
    public User insertUser(User user){
        //设置创建时间
        Date current = new Date();
        user.setCreationDate(current);
        user.setCreatedBy(2L);
        user.setLastUpdateDate(current);
        user.setLastUpdatedBy(2L);
        userMapper.insertUser(user);
        return userMapper.getUser(user.getUserId());
    }

    /**
     * 更新用户 当前版本号和数据库版本号相同时允许更新，并将版本号+1
     * @param user
     * @return
     */
    public User updateUser(User user){
        User oldUser = userMapper.getUser(user.getUserId());
        if(oldUser != null && oldUser.getObjectVersionNumber().equals(user.getObjectVersionNumber())) {
            //更新版本号
            Long newVersion = oldUser.getObjectVersionNumber() + 1L;
            user.setObjectVersionNumber(newVersion);
            //更新修改时间
            Date current = new Date();
            user.setLastUpdateDate(current);
            user.setLastUpdatedBy(4L);
            userMapper.updateUser(user);
        }
        return userMapper.getUser(user.getUserId());
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    public int deleteUser(Long id){
        return userMapper.deleteUser(id);
    }

    /**
     * 获取全部用户（可分页）
     * @param user
     * @return
     */
    public List<User> getAll(User user){
        if(user != null){
            PageHelper.startPage(user.getPage(), user.getRows());
        }
        return userMapper.getAll();
    }

    /**
     * 根据id获取用户
     * @param id
     * @return
     */
    public User getUser(Long id){
        return userMapper.getUser(id);
    }
}
